package com.paper.tiger.datasource.aop;

import com.paper.tiger.datasource.common.DataSource;
import com.paper.tiger.datasource.common.DynamicDataSource;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * [简要描述]: 调用对应方法时的aop，对数据源进行切换
 * [详细描述]:
 *
 * @author ZouHaiBo
 * @version 1.0, 2021/5/21 15:09
 * @since JDK 1.8
 */
public class DataSourceAnnotionMethodIntercept implements MethodInterceptor
{

    private static final Logger log = LoggerFactory.getLogger(DataSourceAnnotionMethodIntercept.class);

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable
    {

        Method method = invocation.getMethod();
        DataSource ds = method.getAnnotation(DataSource.class);

        // 如果方法上面没有 获取类上的 注解
        if (ds == null){
            ds = method.getDeclaringClass().getAnnotation(DataSource.class);
        }

        if (ds == null) {
            DynamicDataSource.setDataSource("master");
            log.debug("set datasource is master" );
        } else {
            DynamicDataSource.setDataSource(ds.value());
            log.debug("set datasource is " + ds.value());
        }
        try {
            return invocation.proceed();
        } finally {
            DynamicDataSource.clear();
            log.debug("clean datasource");
        }
    }
}
